using System.Security.Cryptography.X509Certificates;

using ManageSystemServer.DAO;
using ManageSystemServer.Service;

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;

namespace ManageSystemServer
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<ServerContext>(
                options => options.UseMySql(
                    Configuration.GetConnectionString("db"),
                    new MySqlServerVersion("5.7.30"))
               );
            services.AddControllers();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(option =>
                {
                    var section = Configuration.GetSection("Authentication");
                    var key = new X509SecurityKey(new X509Certificate2(section.GetValue<string>("Certificate")));
                    option.TokenValidationParameters = new()
                    {
                        ValidateAudience = false,
                        ValidateIssuer = true,
                        ValidIssuer = section.GetValue<string>("Issuer"),
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = key,
                        ValidateLifetime = true
                    };
                });
            services.AddAuthorization(option =>
            {
                option.FallbackPolicy = option.DefaultPolicy;
            });
            services.AddSingleton<JwtTokenGenerator>()
                .AddScoped<StudentService>()
                .AddScoped<AdminService>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection()
                .UseRouting()
                .UseAuthentication()
                .UseAuthorization()
                .UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
        }
    }
}
